<?php

namespace app\common\cachemodel;

use app\common\model\BaseCache;
use traits\model\SoftDelete;
use XznsTools\cache\CacheManage;

class AppBlacklist extends BaseCache
{
    protected $table = 'wechat_backup_07_18_14_43_00.app_blacklist';

    protected $cacheModel = 'user.blacklist';

    use SoftDelete;


    public function addData(array $data)
    {
        try
        {
            $id = $this->insertGetId($data);

            $this->listDataAdd($data['uid'], [$id => $id]);
            return true;
        }
        catch (\Exception $e)
        {
            \think\Log::write(__CLASS__ . ' => ' . __FUNCTION__ . '()异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
            return false;
        }
    }


    /**
     * @param array $ids
     * @param array|null $type
     * @param string $sortType
     * @return array
     */
    public function getInfoByIdsInData($ids, $type, $sortType)
    {
        if ($ids)
        {
            $where = ['id' => ['in', $ids]];
        } else
        {
            $where = ['uid' => $type[0]];
        }
        $field = 'uid,black_uid,avatar,nickname,create_time';
        try
        {
            $data = $this
                ->field($field)
                ->where($where)
                ->column($field, 'id');
        }
        catch (\Exception $e)
        {
            $data = [];
        }
        return $data;
    }

    public function delData($uid, $id)
    {
        try
        {
            $this->destroy($id);

            CacheManage::getInstance()->setCacheConfig($this->cacheModel, $id)->rmCache();
            $this->listDataDel($uid, [$id]);
        }
        catch (\Exception $e)
        {
            \think\Log::write(__CLASS__ . ' => ' . __FUNCTION__ . '()异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
        }
    }

    /**
     * 获取黑名单 uid 列表
     * @param $uid
     * @return array
     * @throws \Exception
     */
    public function getBlacklistUids($uid)
    {
        $pageData = $this->getListPage($uid, 'id', ['black_uid']);

        $uids = [];
        foreach ($pageData['data'] as $datum)
        {
            $uidItem = (int)$datum['black_uid'];
            if (!in_array($uidItem, $uids, true))
            {
                $uids[] = $uidItem;
            }
        }

        return $uids;
    }
}